﻿
using Castle.Core.Internal;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.EntityFrameworkCore.Metadata;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;

namespace Coldairarrow.Business.Interface
{
    public class STK_InvPriceInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {

        public List<OL_FilterDTO> Filters;

        public int NoQueryNum { get; set; }
        public STK_InvPriceInterfaceBusiness()
        {
            this.InterfaceName = "账龄价格报表";
            //获取主键字段列表


            //获取字段的映射关系
            tableField = GetMapField("addRow");

            //索引字段
            Keys = GetKeys("addRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();

            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;
        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }
        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 新增更新表
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT  * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置



                SqlDb._conStrings[0] = insertOption.SourceLink;
                List<V_STK_INVENTORYPRICE> V_STK_INVENTORYPRICE = SqlDb.GetListBySql<V_STK_INVENTORYPRICE>(@$"SELECT * FROM {insertOption.SourceData}");
                //价格列表
                List<V_PUR_INSTOCKPRICE> priceList = SqlDb.GetListBySql<V_PUR_INSTOCKPRICE>(@$"SELECT * FROM V_PUR_INSTOCKPRICE");

                //获取存货收发明细的价格金额
                KD_HS_InOutStockInterfaceBusiness kD_HS_InOut = new KD_HS_InOutStockInterfaceBusiness();
                List<HS_NoDimInOutStockDetailRpt> InOutPrice = await kD_HS_InOut.QueryAsync<HS_NoDimInOutStockDetailRpt>(kD_HS_InOut.GetSysReportData, this.SqlDb);
                InOutPrice = InOutPrice.Where(x => !x.FENDPrice.IsNullOrEmpty()).ToList();

                //查询存储类型不为空的物料
                BD_MATInterfaceBusiness bD_MATInterfaceBusiness = new BD_MATInterfaceBusiness();
                List<V_BD_MATERIAL> material = new List<V_BD_MATERIAL>();

                //筛选储备类型不为空的物料信息
                bD_MATInterfaceBusiness.Filters.Clear();
                bD_MATInterfaceBusiness.Filters.Add(
                    new OL_FilterDTO() { ControlId = "67354724a23bbf6d2b15d5e3", DataType = 2, SpliceType = 2, FilterType = 8, Value = "" }
                );
                material = await bD_MATInterfaceBusiness.QueryAsync<V_BD_MATERIAL>(bD_MATInterfaceBusiness.queryOption, bD_MATInterfaceBusiness.tableField, bD_MATInterfaceBusiness.SqlDb);//查询物料

                List<V_STK_INVENTORYPRICE> sourceData = new List<V_STK_INVENTORYPRICE>();//源数据集合
                if (V_STK_INVENTORYPRICE.Count > 0 && InOutPrice.Count > 0)
                {
                    //合并相同行的数量
                    V_STK_INVENTORYPRICE.GroupBy(x => x.FNUMBER + x.FSTOCKNAME + x.FORGNAME).ForEach(g =>
                    {

                        if (g.Count() > 0)//将ID相同的行合并
                        {

                            var o = g.First().DeepClone();
                            //合并数量
                            o.FSUMEQTY = g.Sum(x => x.FSUMEQTY);
                            o.FBASEQTY_0to7 = g.Sum(x => x.FBASEQTY_0to7);
                            o.FBASEQTY_0to15 = g.Sum(x => x.FBASEQTY_0to15);
                            o.FBASEQTY_15to30 = g.Sum(x => x.FBASEQTY_15to30);
                            o.FBASEQTY_30to60 = g.Sum(x => x.FBASEQTY_30to60);
                            o.FBASEQTY_61to67 = g.Sum(x => x.FBASEQTY_61to67);
                            o.FBASEQTY_68to90 = g.Sum(x => x.FBASEQTY_68to90);
                            o.FBASEQTY_90to120 = g.Sum(x => x.FBASEQTY_90to120);
                            o.FBASEQTY_120to180 = g.Sum(x => x.FBASEQTY_120to180);
                            o.FBASEQTY_180to360 = g.Sum(x => x.FBASEQTY_180to360);
                            o.FBASEQTY_360to = g.Sum(x => x.FBASEQTY_360to);

                            o.FBASEPRICE_181to270 = g.Sum(x => x.FBASEPRICE_181to270);
                            o.FBASEPRICE_271to365 = g.Sum(x => x.FBASEPRICE_271to365);
                            o.FBASEQTY_365to = g.Sum(x => x.FBASEQTY_365to);
                            o.FBASEQTY_720to = g.Sum(x => x.FBASEQTY_720to);
                            //获取单价
                            var t = InOutPrice.Where(x => x.FMATERIALID == o.FNUMBER && x.FENDPrice.ToDouble() > 0).ToList();
                            var price = "";
                            if (t.Count > 0)
                            {
                                price = t.Last().FENDPrice;
                                o.PriceSource = "存货明细";
                            }
                            else if (price == "")
                            {
                                var p = priceList.Where(x => x.FMATERIALID == o.FMATERIALID && x.FTYPE == "Pay");
                                if (!p.IsNullOrEmpty() && p.Count() > 0)
                                {
                                    price = p.First().FTAXPRICE;
                                    o.PriceSource = "应付单";
                                }

                            }
                            else if (price == "")
                            {
                                var p = priceList.Where(x => x.FMATERIALID == o.FMATERIALID && x.FTYPE == "Price");
                                if (!p.IsNullOrEmpty() && p.Count() > 0)
                                {
                                    price = p.First().FTAXPRICE;
                                    o.PriceSource = "采购价目";
                                }

                            }
                            //else if (price == "")
                            //{
                            //    var p = priceList.Where(x => x.FMATERIALID == o.FMATERIALID && x.FTYPE == "Receiv");
                            //    if (!p.IsNullOrEmpty() && p.Count() > 0)
                            //    {
                            //        price = p.First().FTAXPRICE;
                            //        o.PriceSource = "应收单";
                            //    }

                            //}
                            //else
                            //{
                            //    var sss = "";

                            //}
                            //计算金额
                            if (price != "")
                            {
                                o.FBASEPRICE = Convert.ToDecimal(price);
                                o.FSUMPRICE = o.FBASEPRICE * o.FSUMEQTY;
                                o.FBASEPRICE_0to7 = o.FBASEPRICE * o.FBASEQTY_0to7;
                                o.FBASEPRICE_0to15 = o.FBASEPRICE * o.FBASEQTY_0to15;
                                o.FBASEPRICE_15to30 = o.FBASEPRICE * o.FBASEQTY_15to30;
                                o.FBASEPRICE_30to60 = o.FBASEPRICE * o.FBASEQTY_30to60;
                                o.FBASEPRICE_61to67 = o.FBASEPRICE * o.FBASEQTY_61to67;
                                o.FBASEPRICE_68to90 = o.FBASEPRICE * o.FBASEQTY_68to90;
                                o.FBASEPRICE_90to120 = o.FBASEPRICE * o.FBASEQTY_90to120;
                                o.FBASEPRICE_120to180 = o.FBASEPRICE * o.FBASEQTY_120to180;
                                o.FBASEPRICE_180to360 = o.FBASEPRICE * o.FBASEQTY_180to360;
                                o.FBASEPRICE_360to = o.FBASEPRICE * o.FBASEQTY_360to;

                                o.FBASEPRICE_181to270 = o.FBASEPRICE * o.FBASEQTY_181to270;
                                o.FBASEPRICE_271to365 = o.FBASEPRICE * o.FBASEQTY_271to365;
                                o.FBASEPRICE_365to = o.FBASEPRICE * o.FBASEQTY_365to;
                                o.FBASEPRICE_720to = o.FBASEPRICE * o.FBASEQTY_720to;
                            }
                            else
                            {
                                o.FBASEPRICE = 0;
                                o.FSUMPRICE = 0;
                                o.FBASEPRICE_0to7 = 0;
                                o.FBASEPRICE_0to15 = 0;
                                o.FBASEPRICE_15to30 = 0;
                                o.FBASEPRICE_30to60 = 0;
                                o.FBASEPRICE_61to67 = 0;
                                o.FBASEPRICE_68to90 = 0;
                                o.FBASEPRICE_90to120 = 0;
                                o.FBASEPRICE_120to180 = 0;
                                o.FBASEPRICE_180to360 = 0;
                                o.FBASEPRICE_360to = 0;

                                o.FBASEPRICE_181to270 = 0;
                                o.FBASEPRICE_271to365 = 0;
                                o.FBASEPRICE_365to = 0;
                                o.FBASEPRICE_720to = 0;
                            }


                            //获取储备类型不为空的项
                            var save = material.Where(x => x.FNUMBER == o.FNUMBER).ToList();
                            if (save.Count > 0)
                            {
                                o.FSAVETYPE = save[0].FSAVETYPE;
                                o.FSTOCKNAME_A = o.FSAVETYPE;
                            }
                            else
                            {
                                o.FSTOCKNAME_A = o.FSTOCKNAME;
                            }

                            o.FID = o.FNUMBER + o.FSTOCKNAME + o.FORGNAME;


                            sourceData.Add(o);

                        }
                    });



                    //按照物料类型分组统计总价
                    var group = from source in sourceData
                                group source by source.FYTPE into grouped
                                select new { FType = grouped.Key, FSum = grouped.Sum(x => x.FSUMPRICE) };

                    foreach (var item1 in group)
                    {
                        sourceData.Where(x => x.FYTPE == item1.FType && !x.FSTOCKNAME.Contains("模具") && !x.FSTOCKNAME.Contains("客退")).ForEach(x => x.FTYPESumPrice = (decimal)item1.FSum);
                    }





                    //获取目标数据
                    List<V_STK_INVENTORYPRICE> targetData = new List<V_STK_INVENTORYPRICE>();//目标据集合
                    Filters.Clear();
                    Filters.Add(
                        new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//F_MO_APPROVEDATE字段过滤单日开始700天前到现在的数据
                    );

                    targetData = await QueryAsync<V_STK_INVENTORYPRICE>(queryOption, tableField, SqlDb);


                    if (this.State > 0 && sourceData.Count > 0)
                    {
                        //更新
                        #region
                        List<V_STK_INVENTORYPRICE> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<V_STK_INVENTORYPRICE>(Keys, "RowId")).ToList();//获取交集(更新项)
                        List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                        ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                        #endregion

                        //新增
                        #region
                        List<V_STK_INVENTORYPRICE> insertItem = sourceData.Except(targetData, new ComparerFromKey<V_STK_INVENTORYPRICE>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                        List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                        ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                        #endregion

                        //删除
                        #region
                        List<V_STK_INVENTORYPRICE> deleteItem = targetData.Except(sourceData, new ComparerFromKey<V_STK_INVENTORYPRICE>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                        List<V_STK_INVENTORYPRICE> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                        //将重复的项也一起加入删除的列表
                        deleteItem.AddRange(repeatItem);
                        //筛选出删除列表中重复的项
                        var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                        deleteItem.AddRange(temp);
                        List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                        ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                        #endregion
                        //同步数据库
                        SqlDBInterfaceBusiness sqlDBInterface = new SqlDBInterfaceBusiness(Keys);
                        sqlDBInterface.ExecuteInterface<V_STK_INVENTORYPRICE>(sourceData, "SD_KD_V_STK_INVENTORYPRICE");
                    }
                    else
                    {
                        throw new Exception("目标/源查询无数据无法执行接口!!");
                    }
                }
                else
                {
                    throw new Exception("目标/源查询无数据无法执行接口!!");
                }

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }


        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //判断对象的字段是否存在，并且类型为N不需要添加新增的
                    if (item.ContainsProperty(c.Value))
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }



}
